import os,sys
import time
from rasplab.common import tcpsrv
import car


class CarServer(object):
	def __init__(self):
		self.car = car.Car()
		pass

	def run(self):
		server = tcpsrv.TcpServer(messagelength=20)
		server.listen(self)

	def command_status(self,status):
		if not status.isdigit():
			return

		if int(status) == 1:
			print 'engine start!'
			self.car.go_forward() #step forward for 0.5s
			time.sleep(0.5)
			self.car.stop()
		else:
			print 'engine stop!'
			self.car.stop()

	def command_data(self,data):
		raw = data.split(';')

		split_strip = lambda s: s.split(':')[1].strip()
		resolve_int = lambda x: int(split_strip(x)) if split_strip(x).isdigit() or (split_strip(x).startswith('-') and split_strip(x)[1:].isdigit()) else 0

		p = resolve_int(raw[0])
		r = resolve_int(raw[1])

		self.car.go(p,r)

		# if p > 0:
		# 	print 'forward'
		# 	self.car.go_forward()
		# else:
		# 	print 'backward'
		# 	self.car.go_backward()

		# print p

	def msg_execute(self,message):
		#print 'execute message: '+message
		#'data|p: 500;r:   0;'
		#'stat|             1'
		messagePiece = message.split('|')
		command = messagePiece[0]
		content = messagePiece[1]

		if command == 'stat':
			self.command_status(content.strip()[:1])
		elif command == 'data':
			self.command_data(content.strip())
		else:
			pass

	def msg_bye(self):
		#self.car.poweroff()
		print 'car is going to stop'
		print 'gpio stopped.'

	def msg_invalid(self,message):
		print 'invalid message detected in machine module'
		print message
		



if __name__ == '__main__':
	s = CarServer()
	s.run()